import csv
import os
from fastapi import HTTPException, FastAPI, Request
from pydantic import BaseModel
from sentence_transformers import InputExample
from starlette import status
from starlette.responses import JSONResponse

app = FastAPI()


def get_input_example(file_name: str) -> list[InputExample]:
    with open(file_name, encoding="utf-8") as fIn:
        reader = csv.DictReader(fIn)
        train_examples = []
        for row in reader:
            score = float(row["score"])
            inp_example = InputExample(texts=[row["sentence1"], row["sentence2"]], label=score)
            train_examples.append(inp_example)
    return train_examples


def rootpath():
    return os.environ['MAIN_FILE_PATH']


def sample_path():
    return rootpath() + "\\data\\sample"


def model_path():
    return rootpath() + "\\data\\models"


class ErrorResponse(BaseModel):
    detail: str


async def general_exception_handler(request: Request, e: Exception):
    if isinstance(e, HTTPException):
        # 如果是HTTPException，使用其status_code和detail
        response = JSONResponse(status_code=e.status_code, content={"message": e.detail})
    else:
        # 否则，使用通用的400 Bad Request响应
        response = JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content={"message": str(e)})
    return response
